import { session, storage } from 'js/util'
import { apiUserRole } from 'js/api'

export default {
  state: {
    userInfo: session.get('userInfo') || {},
    industry: session.get('industry') || 2,
    storeInfo: {},
    userRole: ''
  },
  getters: {
    userInfo: state => state.userInfo,
    storeInfo: state => state.storeInfo,
    token: state => state.userInfo.accessToken,
    mobile: state => state.userInfo.userName,
    nickName: state => state.userInfo.nickName,
    userHeadImg: state => state.userInfo.userHeadImg,
    avatar: state => state.userInfo.userHeadImg,
    storeId: state => state.userInfo.storeId,
    userRole: state => storage.get('userRole'),
    industry: state => state.industry
  },
  actions: {
    // 判断用户角色 1游客 2采购商 3供应商
    fetchUserRole({state}, payload) {
      apiUserRole(payload.token).then(data => {
        if (data && data.role) {
          payload.callback && payload.callback(data.role)
        }
      })
    }
  },
  mutations: {
    // 更新用户信息
    updateUserInfo(state, payload) {
      session.set('userInfo', payload)
      storage.set('userInfo', payload) // 存储当前token数据于本地，防止第三方跳转时，清空session
      storage.set('userRole', payload.userRole)
      state.userInfo = payload
    },
    // 清除用户信息
    clearUserInfo(state) {
      session.remove('userInfo')
      storage.remove('userInfo') // 存储当前token数据于本地，防止第三方跳转时，清空session
      session.remove('message')
      storage.remove('userRole')
      state.userInfo = {}
      state.userRole = ''
    },
    // 更新行业id
    updateUserInfoIndustry(state, industry) {
      session.set('industry', industry)
      state.industry = industry
    },
    // 更新商家头像
    updateStoreInfo(state, payload) {
      state.storeInfo = payload
    }
  }
}
